class DepartmentController < ApplicationController
  before_filter :user_authorize
  before_filter :sys_before_log
  before_filter :privilege_filter,:except=>[:newDepartment,:editDepartment,:getManagerForDepartment]

  def departmentList
    
  end

  #得到部门列表
  def getDepartments
    if params[:query]!=nil
      departments = Department.find(:all,:conditions=>['name like ?','%'+params[:query]+'%'])
    else
      departments = Department.all
    end
    render :text=>departments.to_json,:layout=>false
  end
  #得到部门列表----审批人----后台管理
  def getDepartmentsList
    pageBegin =  params[:start]
    pageEnd =  params[:limit]
    departments = Department.findDepartmentOfBar(params[:name],pageBegin,pageEnd)
    count = Department.findDepartmentOfCount(params[:name]).length
    jsonstr="{totalProperty:"+count.to_s+",root:"+departments.to_json(:include => {:manager=>{:only=>:name}},:only => [:id,:name,:manager_id])+"}"

    render :text=>jsonstr, :layout=>false
  end

  def create
    begin
      departments = Department.new
      departments.name = params[:name]
      departments.save!
      info = 'success'

    rescue Exception => e
      info = e.to_s
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  def edit
    department = Department.find(params[:id])
    render :text=>department.to_json(:include => {:manager=>{:only=>:name}},:only => [:id,:name,:manager_id]),:layout=>false
  end
  #为combox取到属于部门的人员
  def getManagerForDepartment

    #params[:departmentid]---从前台传来的department_id
    manager = Applicant.find_all_by_department_id(params[:departmentid])
    jsonStr = manager.to_json(:only => [:name,:id])
    logger.info jsonStr
    render :text=>jsonStr,:layout=>false
  
  end

  def update
    begin

      department = Department.find(params[:id])
      department.name = params[:name]
      department.manager_id = params[:manager_id]
      department.save!
      info = 'success'

    rescue Exception=>e
      info = e.to_s
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  def delete

    begin
      ids= params[:id][1..params[:id].length-2].split(',');
      for id in ids
        departments = Department.find(id)
        departments.destroy
      end
      info = 'success'
    rescue Exception=>e
      info = e.to_s
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end
  
end
